<?php

function log4debug($s) {
    $myFile = "debug-" . date("j-n-Y") . ".txt";
    $fh = fopen($myFile, 'a');
    fwrite($fh, $s);
    fclose($fh);
}

function count_user() {
    global $CONFIG;
    $query = "SELECT COUNT(*) as user_count FROM {$CONFIG->dbprefix}users_entity";
    $result = safe_select_query($query);
    return $result[0]->user_count;
}

function get_random_fb_users() {
    global $CONFIG;

    $fields = "elgg_u.guid as user_id, fb_dtt_u.facebook_id, elgg_u.username, CONCAT('http://graph.facebook.com/', fb_dtt_u.facebook_id, '/picture?type=large') as avatar_url, elgg_u.name as fullname";
    $query = " SELECT $fields FROM {$CONFIG->dbprefix}users_entity elgg_u, draw_together_fb_users fb_dtt_u ";
    $query .= " WHERE admin = 'no' AND banned = 'no' AND fb_dtt_u.facebook_id != '' ";
    $query .= " AND fb_dtt_u.user_id = elgg_u.guid  ";
    $query .= " ORDER BY RAND() ";
    $query .= " LIMIT 1 ";

    $result = safe_select_query($query);
    return $result[0];
}

function suggest_users_by_keywords($keywords, $user_id = 0) {
    global $CONFIG;
    $fields1 = "elgg_u.guid as user_id, fb_dtt_u.facebook_id, elgg_u.username, CONCAT('http://graph.facebook.com/', fb_dtt_u.facebook_id, '/picture?type=large') as avatar_url, elgg_u.name as fullname ";
    $query = " SELECT $fields1 FROM {$CONFIG->dbprefix}users_entity elgg_u, draw_together_fb_users fb_dtt_u ";
    $query .= " WHERE admin = 'no' AND banned = 'no' AND fb_dtt_u.facebook_id != '' AND elgg_u.guid != $user_id ";
    $query .= " AND (elgg_u.name LIKE '%$keywords%' OR elgg_u.email LIKE '%$keywords%') ";
    $query .= " AND fb_dtt_u.user_id = elgg_u.guid  ";
    $query .= " UNION ";
    $fields2 = "elgg_u.guid as user_id, fb_dtt_u.facebook_id, elgg_u.username, CONCAT('http://profile.ak.fbcdn.net/static-ak/rsrc.php/v2/yo/r/UlIqmHJn-SK.gif') as avatar_url, elgg_u.name as fullname ";
    $query .= " SELECT $fields2 FROM {$CONFIG->dbprefix}users_entity elgg_u, draw_together_fb_users fb_dtt_u ";
    $query .= " WHERE admin = 'no' AND banned = 'no' AND fb_dtt_u.facebook_id = '' AND elgg_u.guid != $user_id  ";
    $query .= " AND (elgg_u.name LIKE '%$keywords%' OR elgg_u.email LIKE '%$keywords%') ";
    $query .= " AND fb_dtt_u.user_id = elgg_u.guid  ";
    $query .= " LIMIT 0,20 ";
    // echo ($query);exit; 
    $result = safe_select_query($query);
    return $result;
}

